﻿#include "WindowsSystemInfo.h"

#include <QDebug>
#include <QProcess>
#include <QFileInfoList>
#include <QDir>


#ifdef Q_OS_WIN
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x502
#endif
#include "windows.h"
#endif

#define GB (1024 * 1024 * 1024)
#define MEMORY_MB (1024 * 1024)
#define MEMORY_KB (1024)

namespace Common {

	WindowsSystemInfo::WindowsSystemInfo(QObject *parent)
		: QObject(parent)
	{
	}

	WindowsSystemInfo::~WindowsSystemInfo()
	{
	}

	double WindowsSystemInfo::getMemoryUsage()
	{
		//获取内存的使用率
		MEMORYSTATUSEX memoryStatus;
		memoryStatus.dwLength = sizeof(MEMORYSTATUSEX);
		GlobalMemoryStatusEx(&memoryStatus);
		qulonglong memoryPhysicalUsed = memoryStatus.ullTotalPhys - memoryStatus.ullAvailPhys;
		return (double)memoryPhysicalUsed / (double)memoryStatus.ullTotalPhys * 100.0;
	}

	void WindowsSystemInfo::getMemoryInfo(double & dTotalMemory, double & dAvailMemory)
	{
#ifdef Q_OS_WIN
		MEMORYSTATUSEX memoryStatus;
		memoryStatus.dwLength = sizeof(MEMORYSTATUSEX);
		GlobalMemoryStatusEx(&memoryStatus);

		dTotalMemory = memoryStatus.ullTotalPhys / MEMORY_MB;

#elif defined(Q_OS_UNIX) && !defined(Q_OS_WASM)
		if (process->state() == QProcess::NotRunning) {
			process->start("cat", QStringList() << "/proc/meminfo");
	}
#endif

	}

	void WindowsSystemInfo::loadHardDiskInfo()
	{
#ifdef Q_OS_WIN
		QFileInfoList list = QDir::drives();
		foreach(QFileInfo dir, list) {
			QString dirName = dir.absolutePath();
			LPCWSTR lpcwstrDriver = (LPCWSTR)dirName.utf16();
			ULARGE_INTEGER liFreeBytesAvailable, liTotalBytes, liTotalFreeBytes;

			if (GetDiskFreeSpaceEx(lpcwstrDriver, &liFreeBytesAvailable, &liTotalBytes, &liTotalFreeBytes))
			{
				QString use = QString::number((double)(liTotalBytes.QuadPart - liTotalFreeBytes.QuadPart) / GB, 'f', 1);
				use += "G";
				QString free = QString::number((double)liTotalFreeBytes.QuadPart / GB, 'f', 1);
				free += "G";
				QString all = QString::number((double)liTotalBytes.QuadPart / GB, 'f', 1);
				all += "G";
				int percent = 100 - ((double)liTotalFreeBytes.QuadPart / liTotalBytes.QuadPart) * 100;

				//insertSize(dirName, use, free, all, percent);
			}
		}
#elif defined(Q_OS_UNIX) && !defined(Q_OS_WASM)
		process->start("df", QStringList() << "-h");
#endif
	}

}